<template>
  <div class="edit-popup">
    <popup ref="popupRef" :title="popupTitle" :async="true" width="550px" @confirm="handleSubmit" @close="handleClose">
      <el-form ref="formRef" :model="formData" label-width="84px" :rules="formRules">
        <el-form-item label="奖品名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入账号" clearable />
        </el-form-item>
        <el-form-item label="数量" prop="num">
          <el-input-number v-model="formData.num" controls-position="right" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :value="1" size="large">正常</el-radio>
            <el-radio :value="0" size="large">停止</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="图片" prop="desc">
          <el-upload class="avatar-uploader" :http-request="uploadFile" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="formData.img" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
    </popup>
  </div>
</template>
<script lang="ts" setup>
import { ElMessage, type FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { addApi, editApi, detailApi } from '@/api/activity/pize'
import { useDictOptions } from '@/hooks/useDictOptions'
import { getRoleAllApi } from '@/api/permission/role'
import feedback from '@/utils/feedback'
import { computed, reactive, ref, shallowRef } from 'vue'
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
  return mode.value == 'edit' ? '编辑奖品' : '新增奖品'
})

const formData = reactive({
  id: '',
  name: '',
  num: 1,
  status: 1,
  img: '',
})

const formRules = reactive({
  name: [
    {
      required: true,
      message: '请输入奖品名称',
      trigger: ['blur'],
    },
  ],
  num: [
    {
      required: true,
      message: '请输入数量',
      trigger: ['blur'],
    },
  ],
})

import type { UploadProps } from 'element-plus'
// import { upload } from '@/api/common'

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {
  formData.img = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = rawFile => {
  if (rawFile.type !== 'image/png') {
    ElMessage.error('必须上传png')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能大于100k')
    return false
  }
  return true
}
const uploadFile = async (options: any) => {
  const fileData = new FormData()
  fileData.append('file_in', options.file) // 确保文件字段名为 file_in

  try {
    const data = await upload(fileData)
    options.onSuccess(data)
    formData.img = data.url
  } catch (error) {
    options.onError(error)
    ElMessage.error('上传失败')
  }
}
const handleSubmit = async () => {
  await formRef.value?.validate()
  mode.value == 'edit' ? await editApi(formData) : await addApi(formData)
  popupRef.value?.close()
  feedback.msgSuccess('操作成功')
  emit('success')
}

const open = (type = 'add') => {
  mode.value = type
  popupRef.value?.open()
}

const setFormData = async (row: any) => {
  const data = await detailApi({
    id: row.id,
  })
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      //@ts-ignore
      formData[key] = data[key]
    }
  }
}

const handleClose = () => {
  emit('close')
}

defineExpose({
  open,
  setFormData,
})
</script>
<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
</style>
